package com.cskaoyan.service.impl;

import com.cskaoyan.bean.data.CommentListData;
import com.cskaoyan.bean.data.CommentPostData;
import com.cskaoyan.bean.data.MarketCommentData;
import com.cskaoyan.bean.data.PageData;
import com.cskaoyan.bean.vo.CommentPostVo;
import com.cskaoyan.mapper.MarketCommentMapper;
import com.cskaoyan.model.MarketComment;
import com.cskaoyan.model.MarketCommentExample;
import com.cskaoyan.model.MarketUser;
import com.cskaoyan.service.CommentService;
import com.cskaoyan.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author Pudding
 * @Date 2024/6/12 22:58
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    UserService userService;

    @Override
    public Map<String, Object> findByGoodsId(Integer goodsId, byte type, int page, int limit) {
        //一个商品对应多个评论，在评论表中有value_id+type(评论类型如果type=0，则是商品评论；如果是type=1，则是专题评论)
        //先找出type=0的，再找value_id=goods_id,也就是该商品对应的多个评论

        //1. 构造查询评论表中的查询条件
        MarketCommentExample example = new MarketCommentExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andTypeEqualTo(type)
                .andValueIdEqualTo(goodsId);
        example.setOrderByClause("add_time desc");
        //2. 开启分页限制
        PageHelper.startPage(page, limit);
        //2.1 查询评论表的list（只有这个下面查询的原始结果放入到PageInfo的构造方法中可以获得一个PageInfo对象，里面封装对应的分页信息）
        List<MarketComment> marketCommentList = commentMapper.selectByExample(example);
        //2.2 将查询原始结果封装到PageInfo对象中
        //PageInfo对象不仅包含了该页list本身信息（即查询结果），还包含了分页的相关信息，这些信息通常是通过 PageHelper 提供的。
        PageInfo<MarketComment> pageInfo = new PageInfo<>(marketCommentList);
        //2.3 通过pageInfo获取分页信息，注意：这个pageinfo携带的list并不是下面data的list，但是没有关系，这两个的分页总数都是一样的
        long total = pageInfo.getTotal();  //查询评论总数

        //3. 查询评论data信息
        //3.1 构造封装data数据的list
        List<MarketCommentData> data = new ArrayList<>();
        if (!marketCommentList.isEmpty()) {
            for (MarketComment marketComment : marketCommentList) {
                //3.2 查询user表的list
                MarketUser marketUser = userService.findById(marketComment.getUserId());
                //3.3 将两张表的数据封装到data中
                MarketCommentData commentData = MarketCommentData.builder()
                        .addTime(new Date())
                        .adminContent(marketComment.getAdminContent())
                        .avatar(marketUser.getAvatar())
                        .content(marketComment.getContent())
                        .id(marketComment.getId())
                        .nickname(marketUser.getNickname())
                        .picList(List.of(marketComment.getPicUrls()))
                        .build();

                //3.4 将数据插入date中
                data.add(commentData);
            }
        }

        //4. 创建一个map封装comment评论的结果集
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", total);
        map.put("data", data);

        return map;
    }

    @Override
    public PageData list(Integer valueId, Byte type, Integer page, Integer limit, Boolean showType) {
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteria = marketCommentExample.createCriteria();
        criteria.andValueIdEqualTo(valueId)
                .andTypeEqualTo(type)
                .andDeletedEqualTo(false);
        //如果showType=true，则只显示有图片的评论
        //showType=false表示显示全部评论
        if (showType) {
            //增加显示图片的条件
            criteria.andHasPictureEqualTo(true);
        }
        marketCommentExample.setOrderByClause("add_time desc");
        //开启分页
        PageHelper.startPage(page, limit);
        //查询评论列表
        List<MarketComment> marketComments = commentMapper.selectByExample(marketCommentExample);

        List<CommentListData> data = new ArrayList<>();
        for (MarketComment marketComment : marketComments) {
            //通过userId查询用户信息
            MarketUser marketUser = userService.findById(marketComment.getUserId());
            Map<String, String> userInfo = new HashMap<>();
            userInfo.put("avatarUrl", marketUser.getAvatar());
            userInfo.put("nickname", marketUser.getNickname());
            //对数据继续封装
            CommentListData commentListData = CommentListData.builder()
                    .addTime(marketComment.getAddTime())
                    .adminContent(marketComment.getAdminContent())
                    .content(marketComment.getContent())
                    .picList(marketComment.getPicUrls())
                    .userInfo(userInfo)
                    .build();
            //添加的List集合中
            data.add(commentListData);
        }


        return PageData.list(data);
    }

    @Override
    public Map<String, Integer> count(Integer valueId, Byte type) {
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        marketCommentExample.createCriteria()
                .andValueIdEqualTo(valueId)
                .andTypeEqualTo(type)
                .andDeletedEqualTo(false);
        List<MarketComment> marketComments = commentMapper.selectByExample(marketCommentExample);
        Map<String, Integer> data = new HashMap<>();
        //统计评论总数
        int allCount = marketComments.size();
        //统计有图片的评论总数
        int hasPicCount = marketComments.stream()
                .filter(marketComment -> marketComment.getHasPicture() == true)
                .toArray().length;
        data.put("allCount", allCount);
        data.put("hasPicCount", hasPicCount);
        return data;
    }

    @Override
    public CommentPostData post(CommentPostVo commentPostVo, Integer userId) {
        Date current = new Date();
        MarketComment marketComment = MarketComment.builder()
                .addTime(current)
                .content(commentPostVo.getContent())
                .picUrls(commentPostVo.getPicUrls())
                .star(commentPostVo.getStar())
                .type(commentPostVo.getType())
                .userId(userId)
                .valueId(commentPostVo.getValueId())
                .updateTime(current)
                .hasPicture(commentPostVo.getHasPicture())
                .build();
        //有选择的插入到数据库中
        commentMapper.insertSelective(marketComment);
        CommentPostData commentPostData = CommentPostData.builder()
                .id(marketComment.getId())
                .addTime(marketComment.getAddTime())
                .content(marketComment.getContent())
                .star(marketComment.getStar())
                .type(marketComment.getType())
                .userId(marketComment.getUserId())
                .valueId(marketComment.getValueId())
                .updateTime(marketComment.getUpdateTime())
                .hasPicture(marketComment.getHasPicture())
                .picUrls(marketComment.getPicUrls())
                .build();
        return commentPostData;
    }


}
